<template>
  <CustomModal
    title="烹饪"
    v-model="visible"
    isTabbar
    :showCancelButton="false"
    :confirmText="$t('public.start')"
    @confirm="modelConfirm"
  >
    <scroll-view class="scroll-content" scroll-y>
      <uni-forms
        ref="uFormRef"
        label-position="top"
        :modelValue="formData"
        :rules="rules"
      >
        <uni-forms-item name="deviceSn" class="forms-item-bottom">
          <template #label>
            <view class="nw-label">{{ $t('recipe.selectCooker') }}</view>
          </template>
          <view class="img-wrap">
            <view
              :class="[
                'li',
                {
                  active: formData.deviceSn === row.sn,
                  disabled: row.status * 1 !== deviceStatus.Idle
                }
              ]"
              v-for="(row, i) in deviceList"
              :key="row"
              @click="handleDeviceClick(row)"
            >
              <image
                :src="
                  formData.deviceSn === row.sn
                    ? getViteImageUrl('recipe/cookingMachineSelected.png')
                    : getViteImageUrl('recipe/cookingMachine.png')
                "
                mode="aspectFit"
                class="device-img"
              />
              <view class="li-text">{{ row.name }}</view>
            </view>
          </view>
          <view v-if="!deviceList.length" class="empty-text">
            无空闲炒菜机...
          </view>
        </uni-forms-item>
        <uni-forms-item name="cookCount" class="forms-item-bottom">
          <template #label>
            <view class="nw-label">{{ $t('recipe.cookingServing') }}</view>
          </template>
          <nw-Input
            v-model="formData.cookCount"
            :label="$t('recipe.cookingServing')"
            type="number"
            verifyType="nzint"
            :maxlength="2"
          ></nw-Input>
        </uni-forms-item>
        <uni-forms-item>
          <template #label>
            <view class="nw-label">{{ $t('recipe.prepareIngred') }}</view>
          </template>
          <view class="ul">
            <view class="li uss-form-select" v-for="(row, i) in 4" :key="row">
              <view class="li-label">
                {{ i + 1 }}号{{ $t('recipe.ingredBox') }}:
              </view>
              <view class="label-text">
                {{
                  allIngredList[i]?.totalGoal
                    ? allIngredList[i]?.totalGoal + 'g'
                    : ''
                }}
              </view>
              <view class="li-label-text">{{ allIngredList[i]?.name }}</view>
              <!-- <zxz-uni-data-select
                v-model="formData.ingredStyles[i]"
                :localdata="ingredLists[i]"
                placeholder="选择"
                :emptyTips="$t('system.noOption')"
                :clear="true"
                :disabled="false"
                dataKey="ingredientName"
                dataValue="target"
                @change="handleRoleChange"
              ></zxz-uni-data-select> -->
            </view>
          </view>
        </uni-forms-item>
      </uni-forms>
    </scroll-view>

    <up-toast ref="uToastRef" />
  </CustomModal>
  <PrepareRecipeTip
    v-if="prepareRecipeTipVisible"
    v-model="prepareRecipeTipVisible"
  />
</template>

<script setup>
import PrepareRecipeTip from './PrepareRecipeTip.vue'
import { deviceProtocolEquipmentService } from '@/service/deviceProtocolEquipmentService.js'
import { deviceProtocolRecipeService } from '@/service/deviceProtocolRecipeService.js'

defineOptions({
  name: 'SelectDevice',
  inheritAttrs: false
})

const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  row: {
    type: Object,
    default: () => {}
  }
})
const visible = defineModel({
  type: Boolean,
  default: false
})
const emit = defineEmits(['confirm'])
const uToastRef = ref(null)

const deviceStore = useDeviceStore()
const { bindDeviceList } = storeToRefs(deviceStore)
const { cookingItemList } = storeToRefs(useCookingStore())
const { userInfo } = storeToRefs(useUserStore())
const uFormRef = ref(null)
const formData = ref({
  deviceSn: '',
  cookCount: 1
  // ingredStyles: []
})
// 校验规则
const rules = {
  deviceSn: {
    rules: g_rules.selectRule(g_t('recipe.cooker'))
  },
  cookCount: {
    rules: g_rules.cookingServing
  }
}
const deviceStatus = g_i.device.DeviceStatus
const deviceList = computed(() => {
  return bindDeviceList.value
  // return bindDeviceList.value.filter(
  //   item => item.status * 1 === deviceStatus.Idle
  // )
})
const allIngredList = ref([])
const ingredLists = ref([])
let deviceRow = ref({})
const prepareRecipeTipVisible = ref(false)

// watch(
//   [() => allIngredList.value, () => formData.value.ingredStyles],
//   (nv, ov) => {
//     console.log('nv', nv)
//     // 动态匹配每个下拉框的食材数据
//     for (let i = 0; i < 4; i++) {
//       const ingredStyles = [...formData.value.ingredStyles]
//       ingredStyles.splice(i, 1)
//       ingredLists.value[i] = nv[0].filter((item, j) => {
//         return !ingredStyles.includes(item.target)
//       })
//     }
//     console.log('ingredLists.value', ingredLists.value)
//   },
//   {
//     deep: true
//   }
// )

onMounted(_ => {
  // 如果只有一个空闲则默认选中
  const idleDeviceList = deviceList.value.filter(
    item => item.status * 1 === deviceStatus.Idle
  )
  if (idleDeviceList.length === 1) {
    deviceRow.value = idleDeviceList[0]
    formData.value.deviceSn = idleDeviceList[0].sn
  }
  getRecipeData()
})

function getRecipeData() {
  allIngredList.value = (props.row.stepList || []).filter(item => {
    if (item.ingredientType === 'material') {
      // 计算步骤食材的总重量
      item.totalGoal = item?.materialList.reduce((prev, curr) => {
        return prev + curr.goal
      }, 0)
      return true
    }
  })
  console.log('allIngredList.value', allIngredList.value)
}

const handleDeviceClick = row => {
  console.log('handleDeviceClick', row)
  if (row.status * 1 !== deviceStatus.Idle) {
    uToastRef.value.show({
      type: 'error',
      message: '该炒菜机非空闲状态，请选择其他炒菜机'
    })
    return
  }
  deviceRow.value = row
  formData.value.deviceSn = row.sn
}

const modelConfirm = async e => {
  uFormRef.value
    .validate()
    .then(res => {
      console.log('success', res)
      console.log('props.row', props.row)
      // console.log('formData.value.ingredStyles', formData.value.ingredStyles)
      // 检查食材一致性
      // if (
      //   formData.value.ingredStyles.filter(Boolean).length !==
      //   allIngredList.value.length
      // ) {
      //   uToastRef.value.show({
      //     type: 'error',
      //     message: '已有菜谱食材与选择的食材盒不一致，请重新选择'
      //   })
      //   return
      // }
      // 更新设备信息的调料名称与调料编码
      console.log('设备信息（前）：', deviceRow.value)
      console.log('步骤食材信息（前）：', allIngredList.value)
      deviceRow.value.peripheralList.forEach(item => {
        if (item.type === 1) {
          const ingredItem =
            allIngredList.value[parseInt(item.tag.substring(2)) - 1]
          if (ingredItem) {
            item.ingredientName = ingredItem.ingredientName
            item.ingredientCode = ingredItem.target
          } else {
            item.ingredientName = ''
            item.ingredientCode = ''
          }
        }
      })
      console.log('设备信息（后）：', deviceRow.value)

      prepareRecipeTipVisible.value = true
      // const { data } = await g_api.user.apiGetSystemTime()
      // 烹饪记录存储
      cookingItemList.value.push(
        g_i.apiDataFormat(
          {
            cookingId: g_utils.getUuid(),
            deviceSn: formData.value.deviceSn,
            deviceName: deviceRow.value.name,
            recipeId: props.row.id,
            recipeName: props.row.name,
            cookCount: formData.value.cookCount,
            tasteStyle: props.row.tasteStyle,
            operatorUserId: userInfo.value.userId,
            createTime: Date.now()
          },
          g_i.cooking.cookItemInfo
        )
      )
      // 电子称需要在发送菜谱之前下发，需要先确认设备绑定的电子称信息，绑定的才发
      if (deviceRow.value.bindElectronic) {
        const weights = Object.assign(
          {},
          ...Array.from({ length: 4 }, (_, i) => ({
            [`weight${i + 1}`]: allIngredList.value[i]?.totalGoal || 0
          }))
        )
        deviceProtocolEquipmentService
          .electronicScaleFoodPreparation(formData.value.deviceSn, weights)
          .then(r => {
            console.log('electronicScaleFoodPreparation-发送消息成功：', r)
          })
          .catch(e => {
            console.log('electronicScaleFoodPreparation-发送消息失败：', e)
            uToastRef.value.show({
              type: 'error',
              message: e
            })
          })
      }

      // 执行设备协议操作:下发菜谱、开始炒菜、油烟机命令
      deviceProtocolRecipeService
        .sendRecipe(deviceRow.value, props.row)
        .then(r => {
          console.log('sendRecipe-发送消息成功：', r)
          // 开始炒菜
          deviceProtocolRecipeService
            .startCooking(formData.value.deviceSn, props.row.id)
            .then(r => {
              console.log('startCooking-发送消息成功：', r)
              // 更新设备的状态值为炒菜中
              deviceStore.updateDeviceStatus(
                formData.value.deviceSn,
                g_i.device.DeviceStatus.Cooking
              )
              visible.value = false
              emit('confirm')
            })
            .catch(e => {
              console.log('startCooking-发送消息失败：', e)
              uToastRef.value.show({
                type: 'error',
                message: e
              })
              prepareRecipeTipVisible.value = false
            })
          // 发送油烟机指令
          if (deviceRow.value.bindOil) {
            deviceProtocolEquipmentService
              .rangeHoodFanControl(formData.value.deviceSn, 1, 1)
              .then(r => {
                console.log('rangeHoodFanControl-发送消息成功：', r)
              })
              .catch(e => {
                console.log('rangeHoodFanControl-发送消息失败：', e)
                uToastRef.value.show({
                  type: 'error',
                  message: e
                })
              })
          }
        })
        .catch(e => {
          console.log('sendRecipe-发送消息失败：', e)
          uToastRef.value.show({
            type: 'error',
            message: e
          })
          prepareRecipeTipVisible.value = false
        })
    })
    .catch(err => {
      console.log('err', err)
    })
}

// const handleRoleChange = _ => {
//   console.log('handleRoleChange:', _, formData.value.ingredStyles)
// }
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.scroll-content {
  .nw-label {
    margin-top: 28rpx;
    margin-bottom: 16rpx;
    font-weight: bold;
    font-size: 18rpx;
  }
  .forms-item-bottom {
    margin-bottom: 0;
  }
}

.img-wrap {
  display: flex;
  flex-wrap: wrap;

  .li {
    width: 108rpx;
    height: 108rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 24rpx 8rpx 18rpx;
    background-color: var(--body-theme);
    border: 1rpx solid var(--body-theme);
    box-sizing: border-box;
    &.disabled {
      background-color: #eff2f7;
      border: 1rpx solid #eff2f7;
    }
    + .li {
      margin-left: 16rpx;
    }
    &:nth-child(4n + 1) {
      margin-left: 0;
    }
    &:nth-child(n + 5) {
      margin-top: 16rpx;
    }
    &.active {
      background-color: #e7f9f3;
      color: var(--main-theme);
      border-color: var(--main-theme);
      .li-text {
        color: var(--main-theme);
      }
    }
    .device-img {
      flex-shrink: 0;
      display: block;
      width: 36rpx;
      height: 36rpx;
    }
    .li-text {
      margin-top: 14rpx;
      line-height: 16rpx;
      font-size: 16rpx;
      font-weight: 400;
      color: var(--color-999);
    }
  }
}

.empty-text {
  line-height: 24rpx;
  font-size: 18rpx;
  font-weight: 400;
  text-align: center;
  color: var(--color-333);
}

.ul {
  .li {
    display: flex;
    align-items: center;
    + .li {
      margin-top: 12rpx;
    }
  }
  .li-label {
    flex-shrink: 0;
    width: 90rpx;
    margin-right: 12rpx;
    font-size: 18rpx;
    font-weight: 400;
    color: var(--color-333);
  }

  .label-text {
    min-width: 80rpx;
    min-height: 32rpx;
    line-height: 32rpx;
    margin-right: 12rpx;
    padding: 0 10rpx;
    font-size: 18rpx;
    font-weight: 400;
    text-align: center;
    background-color: var(--body-theme);
    color: var(--color-333);
    @extend .text-wrap;
  }

  .li-label-text {
    font-size: 18rpx;
    font-weight: 400;
    color: var(--color-333);
    @extend .text-wrap;
  }
}

// zxz-uni-data-select多选择框-样式
.uss-form-select :deep(.uni-stat__select) {
  .uni-select {
    border: 1rpx solid var(--sub-theme) !important;
    background-color: var(--bg-color) !important;
    border-radius: 8rpx !important;
  }
}
</style>
